package util;

import constant.SystemConstant;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;

/**
 * @author ‘洋毛’
 * @version 1.0
 * @description: TODO
 * @date 2021/12/11 19:19
 */
public class SystemUtil {

    public static String md5(String source) {

        if (source == null || source.length() == 0) {
            throw new RuntimeException(SystemConstant.MESSAGE_STRING_INVALIDATE);
        }

        // 获取MessageDigest对象
        String encrypt = "md5";

        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance(encrypt);

            byte[] input = source.getBytes();

            // 执行加密
            byte[] output = messageDigest.digest(input);

            // 创建BigInteger对象
            int signStr = 1;
            BigInteger bigInteger = new BigInteger(signStr, output);

            // 按照十六进制将bigInteger转换为字符串
            int radix = 16;
            String encoding = bigInteger.toString(radix).toUpperCase(Locale.ROOT);

            return encoding;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return null;

    }


    /**
     * @param request
     * @return boolean true：是Ajax请求
     * false：不是Ajax请求
     * @description: 判断当前请求是否为Ajax请求
     */
    public static boolean judgeRequestType(HttpServletRequest request) {

        //1.获取请求消息头
        String acceptHeader = request.getHeader("Accept");
        String xRequestHeader = request.getHeader("X-Requested-With");

        //2.判断
        return (acceptHeader != null && acceptHeader.contains("application/json")) || (xRequestHeader != null && xRequestHeader.equals("XMLHttpRequest"));

    }
}
